package com.ruimei.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruimei.entitys.Parent;
import com.ruimei.entitys.ParentRegisterVo;
import com.ruimei.entitys.Student;
import com.ruimei.entitys.Teacher;
import com.ruimei.mapper.RmTeacherMapper;
import com.ruimei.service.IParentService;
import com.ruimei.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags={"登录"})
public  class LoginController
{
  @Resource
  RmTeacherMapper rmTeacherMapper;
  @Resource
  IParentService user;

  @Resource
  private RedisTemplate<String,String> redisTemplate;


  @PostMapping({"/login"})
  @ApiOperation(value="W登录", notes="通过身份证或者手机号")
  public Map<String, Object> login(String userName, String secretkey)
  {
    Map<String, Object> map = new HashMap<String, Object>();
    JSONObject jsonObject = new JSONObject();
    Teacher teacher = null;
    if (userName.length() == 18) {
      teacher = this.rmTeacherMapper.getTeacherByuserName(userName);
    } else if (userName.length() == 11) {
      teacher = this.rmTeacherMapper.getTeacherByPhoneNo(userName);
    }

    if (teacher != null)
    {
      if (Md5Encrypt.MdPwd(secretkey, teacher.getSalt()).equals(teacher.getSecretkey()))
      {
        Teacher teacher1 = new Teacher();
        teacher1.setId(teacher.getId());
        rmTeacherMapper.updateTeacherTime(teacher1);
        if(!redisTemplate.hasKey(teacher.getId())){
          redisTemplate.opsForValue().set(teacher.getId(),JSONObject.toJSONString(teacher));
        }
        jsonObject.put("user",teacher);
        jsonObject.put("token", Base64Encoder.encoder("teacher_"+teacher.getId()));
        map.put("status", Boolean.valueOf(true));
        map.put("message", "登录成功");
        map.put("data",jsonObject);

        return map;
      }
      map.put("status", Boolean.valueOf(false));
      map.put("message", "密码错误");
      return map;
    }
    map.put("status", Boolean.valueOf(false));
    map.put("message", "用户名不存在");
    return map;
  }
  

  @ApiOperation("通過账号登陸(userName or phoneNo/secretkey)")
  @PostMapping({"/loginByPass"})
  public Map<String, Object> loginByPass (Parent parent)
  {
    boolean firsted = false;
    String salt = this.user.selectUser(parent);
    Map<String, Object> map = new HashMap();
    Map<String, Object> data = new HashMap();
    if (StringUtils.isNotBlank(salt))

    {
      parent.setSalt(salt);
      Parent parent1 = this.user.login(parent);
      if (parent1 != null)
      {

        int num = parent1.getFirsted();
        if(num == 1){
          firsted = true;
        }
        data.put("student", JSONUtils.jsonToList(redisTemplate.opsForValue().get("student_"+parent1.getId()),Student.class));
        data.put("firsted",firsted);
        data.put("token",Base64Encoder.encoder("parent_"+parent1.getId()));
        data.put("status",true);
        map.put("message", "登陆成功，即将跳转");
        map.put("data",data);
        map.put("parent",parent1.getId());
        map.put("status",true);
        map.put("token", Base64Encoder.encoder("parent_"+parent1.getId()));
        return map;
      }
      map.put("message", "密码错误");
      map.put("status", false);
      return map;
    }
    map.put("message", "您的登陆账号与系统账号不匹配,请联系管理员");
    map.put("status", false);
    return map;
  }
  

  
  @ApiOperation("得到家长信息")
  @PostMapping({"/getParentInfo"})
  public synchronized  JSONObject getParentInfo(HttpServletRequest request)
  {
    Parent parent;
    JSONObject jsonObject = new JSONObject();
    String id = TokenUtils.getParentId(request);
    if(StringUtils.isNotBlank(id)){
      if(redisTemplate.hasKey(id)){
        net.sf.json.JSONObject sfObject = net.sf.json.JSONObject.fromObject(redisTemplate.opsForValue().get(TokenUtils.getParentId(request)));
        parent = (Parent) net.sf.json.JSONObject.toBean(sfObject,Parent.class);
        jsonObject.put("data",parent);
        jsonObject.put("status",true);
        return jsonObject;
      }
    }
    return null;
  }

  @PostMapping("/parentRegister")
  @ApiOperation(value = "家长注册")
  public JSONObject parentRegister(ParentRegisterVo parentRegisterVo){
    JSONObject object = new JSONObject();
    Map<String,Object> data = new HashMap<>();
    //首先检查验证码是否正确
    if(redisTemplate.hasKey("code_"+parentRegisterVo.getPhoneNo())){
      String code = redisTemplate.opsForValue().get("code_"+parentRegisterVo.getPhoneNo());
      if(code.equals(parentRegisterVo.getCode())){
        return user.parentRegister(parentRegisterVo);
      }
      else{
        data.put("msg","验证码输入错误，请重新输入！");
        data.put("status",false);

        object.put("status",true);
        object.put("data",data);
        return object;
      }
    }
    data.put("msg","请先获取短信验证码！");
    data.put("status",false);
      object.put("status",true);
      object.put("data",data);
      return object;
  }

  @GetMapping("/getRegisterCode/{phoneNo}")
  @ApiOperation(value = "获取注册时的验证码")
  public JSONObject getRegisterCode(@PathVariable(value = "phoneNo") String phoneNo) throws ClientException {
      String code = RandomStringUtils.random(4, "0123456789");
      JSONObject object = new JSONObject();
    if(!redisTemplate.hasKey("code_"+phoneNo)){
      SendSmsResponse sendSmsResponse = SmsUtils.sendSms(phoneNo,code );
      if(sendSmsResponse.getCode().equals("OK")){
        redisTemplate.opsForValue().set("code_"+phoneNo,code,5, TimeUnit.MINUTES);
        object.put("status",true);
        object.put("msg","短信发送成功！");
        object.put("data","true");
        return object;
      }
      else{
        object.put("status",true);
        object.put("msg","短信服务繁忙，请稍后再试！");
        object.put("data","false");
        return object;
      }
    }
    object.put("status",true);
    object.put("msg","请不要频繁获取短信验证码！");
    object.put("data","false");
    return object;

  }

  @GetMapping("/getChild")
  @ApiOperation(value = "重新获取学生")
  public JSONObject getChild(HttpServletRequest request){
    JSONObject data = new JSONObject();
    JSONObject object = new JSONObject();
    String id = TokenUtils.getParentId(request);
    if(redisTemplate.hasKey("student_"+id)){
      redisTemplate.delete("student_"+id);
       object = user.selectCurrentParentChild(id);
      redisTemplate.opsForValue().set("student_"+id,JSONObject.toJSONString(object));
      data.put("status",true);
      data.put("data",object);
      return  data;
    }
    object.put("status",false);
    object.put("msg","不能获取到该家长的绑定学生信息");
    data.put("status",true);
    data.put("data",object);
    return  data;
  }

  public JSONObject getChilds(HttpServletRequest request,RedisTemplate<String,String> redisTemplates,IParentService parentService){
    JSONObject data = new JSONObject();
    JSONObject object = new JSONObject();
    String id = TokenUtils.getParentId(request);
    System.out.println(redisTemplates.hasKey("student_"+id));
    if(redisTemplates.hasKey("student_"+id)){
      redisTemplates.delete("student_"+id);
      object = parentService.selectCurrentParentChild(id);
      redisTemplates.opsForValue().set("student_"+id,JSONObject.toJSONString(object));
      data.put("status",true);
      data.put("data",object);
      return  data;
    }
    object.put("status",false);
    object.put("msg","不能获取到该家长的绑定学生信息");
    data.put("status",true);
    data.put("data",object);
    return  data;
  }


}
